import React, { useState, useImperativeHandle, forwardRef } from 'react';

import { Select, Tag } from 'antd';
import { IFilter } from '@/pages/SelfQuery/type';
import { OperatorFilterTypes } from './constants';
import {  DATA_ACTION_TYPE } from '@/pages/SelfQuery/constants';

interface FilterValueSelectProps {
  name: string;
  text: string;
  visualType: string;
  options: Array<{ value: string; label: string }>;
  ref?: any;
  cRef?: any;
  defaultValue: any;
  onFilter: (key: string, filters?: IFilter[] | undefined) => void
}

const FilterValueSelect: React.FC<FilterValueSelectProps> = (props, ref) => {
  const {
    name,
    text,
    options,
    visualType,
    cRef,
    defaultValue,
    onFilter
  } = props;
  const [selectValue, setSelectValue] = useState<Array<any>>(defaultValue); // 选中的值 默认使用传进来的默认筛选条件

  // 重置方法
  useImperativeHandle(cRef, () => ({
    clear: () => {
      setSelectValue([]);
    },
  }));

  // 下拉选择发生变化
  const handleChange = (selects: any) => {
    setSelectValue(selects)
    let filters: IFilter[] = [];
    selects.map((value: string) => {
      const filter: IFilter = {
        name: name,
        operator: OperatorFilterTypes.Regexp,
        type: 'filter',
        value: value.replace(/\((.+?)\)/g, ''), // 剔除包含的ID字段
        sqlType: 'STRING',
        action: DATA_ACTION_TYPE.filter,
        visualType: visualType,
        isCustomFilter: true, //标识是自定义表单的过滤
        isOr: true,
      };
      filters.push(filter);
    });

    onFilter(name, filters)
  };

  const tagRender = (props: any) => {
    const { label, closable, onClose } = props;
    return (
      <Tag color="blue" closable={closable} onClose={onClose} style={{ marginRight: 3 }}>
        {label}
      </Tag>
    );
  };

  return (
    <div
      style={{
        display: 'flex',
        marginBottom: 24,
      }}
    >
      <span
        style={text.length >= 4 ? {
          flex: '0 0 80px',
          lineHeight: '32px',
          overflow:'hidden',
          textOverflow:'ellipsis',
          whiteSpace:'nowrap',
        }: {
          flex: '0 0 50px',
          lineHeight: '32px',
          overflow:'hidden',
          textOverflow:'ellipsis',
          whiteSpace:'nowrap',
        }}
      >
        {text}：
      </span>
      <Select
        mode="multiple"
        tagRender={tagRender}
        style={{ width: '100%' }}
        value={selectValue}
        options={options}
        onChange={handleChange}
      />
    </div>
  );
};
// @ts-ignore
export default forwardRef(FilterValueSelect);
